package de.uni_saarland.coli.doclists.index.filesystem;

/**
 * 
 * @author stefan
 * 
 *         Helpers do add and extract basic types from byte arrays
 */
public class FilesystemHelper {

	public static final int LengthOfLong = 8;
	public static final int LengthOfInt = 4;

	/**
	 * Adds a long(8 bytes) to the byte array starting at the specified index
	 * 
	 * @param bytes
	 *            the byte array ( minimal size : startIDX + 8)
	 * @param num
	 *            the long to add
	 * @param startIDX
	 *            the first index of the number in the byte array
	 */
	public static void addLongToByteArray(byte[] bytes, long num, int startIDX) {
		for (int i = 0; i < LengthOfLong; i++) {
			bytes[7 - i + startIDX] = (byte) (num >>> (i * 8));
		}
	}

	/**
	 * Extracts a long from the byte array starting at the specified index
	 * 
	 * @param bytes
	 *            the byte array ( minimal size : startIDX + 8)
	 * @param startIDX
	 *            the first index of the number in the byte array
	 * @return a long extracted from the byte array
	 */
	public static long getLongFromByteArray(byte[] bytes, int startIDX) {
		long num = 0;
		for (int i = startIDX; i < startIDX + LengthOfLong; i++) {
			num <<= 8;
			num ^= (long) bytes[i] & 0xFF;
		}

		return num;
	}

	/**
	 * Adds an int(8 bytes) to the byte array starting at the specified index
	 * 
	 * @param bytes
	 *            the byte array ( minimal size : startIDX + 4)
	 * @param num
	 *            the int to add
	 * @param startIDX
	 *            the first index of the number in the byte array
	 */
	public static void addIntToByteArray(byte[] bytes, int num, int startIDX) {
		for (int i = 0; i < LengthOfInt; i++) {
			bytes[3 - i + startIDX] = (byte) (num >>> (i * 8));
		}
	}

	/**
	 * Extracts an int from the byte array starting at the specified index
	 * 
	 * @param bytes
	 *            the byte array ( minimal size : startIDX + 4)
	 * @param startIDX
	 *            the first index of the number in the byte array
	 * @return an int extracted from the byte array
	 */
	public static int getIntFromByteArray(byte[] bytes, int startIDX) {
		int num = 0;

		for (int i = startIDX; i < startIDX + LengthOfInt; i++) {
			num <<= 8;
			num ^= (int) bytes[i] & 0xFF;
		}

		return num;
	}

}
